package org.example.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.mysql.cj.util.StringUtils;
import org.example.entity.Material;
import org.example.exception.ErrorEnum;
import org.example.exception.ServiceException;
import org.example.mapper.MaterialMapper;
import org.example.param.MaterialParam;
import org.example.service.MaterialService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Map;

@Service
public class MaterialServiceImpl implements MaterialService {

    @Resource
    MaterialMapper materialMapper;

    @Override
    public Map<String, Object> save(Material material) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("name", material.getName());
        if (materialMapper.exists(queryWrapper)) {
            throw new ServiceException(ErrorEnum.MATERIAL_EXISTS);
        }
        materialMapper.insert(material);
        return success();
    }

    @Override
    public Map<String, Object> page(MaterialParam param) {
        IPage<Material> page = new Page<>(param.getCurrent(), param.getSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        if (!StringUtils.isNullOrEmpty(param.getMaterialName())) {
            queryWrapper.like("name", param.getMaterialName());
        }
        if (param.getLowStock() == null && param.getHighStock() != null) {
            queryWrapper.le("stock", param.getHighStock());
        }
        if (param.getLowStock() != null && param.getHighStock() == null) {
            queryWrapper.ge("stock", param.getLowStock());
        }
        if (param.getLowStock() != null && param.getHighStock() != null) {
            queryWrapper.between("stock", param.getLowStock(), param.getHighStock());
        }
        page =  materialMapper.selectPage(page, queryWrapper);
        return success(page);
    }

    @Override
    public Map<String, Object> disable(Material material) {
        materialMapper.updateById(material);
        return success();
    }
}
